from selenium import webdriver

from selenium.webdriver.common.by import By
import time

from selenium.webdriver.support.select import Select


class CommonUtils:
    def __init__(self):

        pass

    def open_browser(self, url, type="谷歌"):
        self.dr = None
        # print(1)
        if self.dr is None:
            if type == 'gg' or type == 'chrome' or type == '谷歌':
                self.dr = webdriver.Chrome()
            elif type == 'ff' or type == 'firefox' or type == '火狐':
                self.dr = webdriver.Firefox()
            else:
                print('不支持浏览器')
                exit()

        self.dr.implicitly_wait(3)
        self.dr.maximize_window()
        self.dr.get(url)

        print('打开{}浏览器输入网址{}'.format(type, url))

    def clear_text(self, target):
        self._find_element(target).clear()

    def _find_element(self, target):
        by, value = target.split('=>')
        # dr.find_element(BY.ID)
        ele = self.dr.find_element(getattr(By(), by.upper()), value)
        return ele

    def input(self, target, content):
        self._find_element(target).send_keys(content)

    def click(self, target):
        """
        点击
        :param target:
        :return:
        """
        self._find_element(target).click()

    def deleteCookieRefresh(self):
        self.dr.delete_all_cookies()
        self.dr.refresh()

    def sleep(self, target: float):
        time.sleep(float(target))

    def refresh(self):
        self.dr.refresh()

    # 选择下拉框
    def select_scope(self, target, text):
        element = self._find_element(target)
        se_obj = Select(element)
        se_obj.select_by_visible_text(text)

    #  iframe-切入
    def iframeCutIn(self, target):
        iframe = self._find_element(target)
        self.dr.switch_to.frame(iframe)

    #  iframe-切出
    def iframeCutOut(self):
        self.dr.switch_to.parent_frame()

    # TODO alert弹窗

    def check_element_is_exist(self, target, expect):
        accept = ''
        try:
            self._find_element(target)
            accept = "True"
        except Exception as e:
            accept = "False"

        if accept == expect:
            print('case pass')
        else:
            print('case fail')

    def check_element_equal(self, target, expect):

        text = self._find_element(target).text

        if expect in text:
            print('case pass')
        else:
            print('case fail')

    def close(self):
        self.dr.close()
